import {
  addUserApi,
  deleteUserApi,
  editUserApi,
  getUserListApi,
  type getUserParams,
  type UserResponse,
  type UserStructure
} from "@/api/user.ts"

export const useUseStore = defineStore("user", () => {
  const state = reactive<UserResponse>({
    list: [],
    total: 0
  })

  const getUserList = async (params: getUserParams) => {
    const res = await getUserListApi(params)
    const { data } = res
    state.list = data.list
    state.total = data.total
  }

  const addUser = async (data: UserStructure & getUserParams) => {
    const { page, pageSize, ...user } = data
    const res = await addUserApi(user)
    if (res.code === 200) {
      getUserList({ page, pageSize })
    }
  }

  const editUser = async (data: UserStructure & getUserParams) => {
    const { page, pageSize, ...user } = data
    const res = await editUserApi(user)
    if (res.code === 200) {
      getUserList({ page, pageSize })
    }
  }

  const deleteUser = async (data: UserStructure & getUserParams) => {
    const { id, page, pageSize } = data
    const res = await deleteUserApi(id)
    if (res.code === 200) {
      getUserList({ page, pageSize })
    }
  }

  return {
    state,
    getUserList,
    addUser,
    editUser,
    deleteUser
  }
})
